#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <stdbool.h>
static int number = 0;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *do_thread(void *arg)
{
    // 生产的数量
    int cnt = atoi((char *)arg);

    int i;
    
    for (i = 0; i < cnt; i++)
    {
        pthread_mutex_lock(&mutex);

        printf("thread [%d] produce a product, product number is %d\n", pthread_self(), ++number);
        pthread_mutex_unlock(&mutex);
    }

}

int main(int argc, char const *argv[])
{
    // 根据传参创建线程
    int i;
    pthread_t tid;
    bool is_exit = false;
    // 记录总的生产 的产品数量
    int total_of_product = 0;

    // 记录总的消费的产品数量
    int total_of_consume = 0;
    for (i = 0; i < argc; i++)
    {
        total_of_product += atoi(argv[i]);
        pthread_create(&tid, NULL, do_thread, (void *)argv[i]);
    }


    //主线程进行消费
    while(1) {
        //竞争到锁才能访问number
        pthread_mutex_lock(&mutex);
        while(number > 0) {
            total_of_consume++;
            printf("consumer a product, product number is %d \n", --number);
            is_exit = total_of_consume >= total_of_product; 
            sleep(1);
        }
        pthread_mutex_unlock(&mutex);
        if (is_exit) {
            break;
        }
    }
    return 0;
}
